package org.Component;

import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

public class ScrollBar extends JButton {

    //鼠标点击时的坐标
    int nowy = 0;
    //判断鼠标是否按下
    boolean isPressed = false;
    //下限
    public int limitY = 550;

    public ScrollBar() {
        setBounds(990,0,10,50);

        //鼠标移动事件
        addMouseMotionListener(new MouseMotionListener() {

            @Override
            public void mouseDragged(MouseEvent e) {
                if(isPressed){
                    //滑动条的位置变化公式,鼠标当前坐标-按下时的坐标+滑动条的坐标
                    int dv=e.getY()-nowy+getY();
                    if(dv>=0&&dv<=limitY-50) {
                        setLocation(getX(),dv);
                    }
//                    System.out.println(e.getY());

                }
                System.out.println("dragged");
            }

            @Override
            public void mouseMoved(MouseEvent e) {

            }
        });

        //鼠标点击事件
        addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e) {
                nowy = e.getY();
//                Bnowy = getY();
                isPressed = true;
                System.out.println("pressed");

            }

            @Override
            public void mouseReleased(MouseEvent e) {
                isPressed = false;
                System.out.println("released");
            }

        });

    }

    public void run() {
        if(getY()<=0) setLocation(990,0);
        if(getY()>=600) setLocation(990,550);
    }

}
